<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1 style="text-align: center;">登陆</h1>
  <div style="display: flex;justify-content: center;align-items: center;">
    <form id='form'>
      {% csrf_token%}
      {% for field in form %}
        <div>
          <label for='{{field.auto_id}}'>{{field.label}}</label>
          {{field}}<span></span>
        </div>
      {% endfor %}
      <label for="avata">
        <input type="file" id='avata'  multiple="multiple">
        <img width="60" height="60" id="avata_img" src="https://www.baidu.com/img/flexible/logo/pc/result@2.png" alt="">
      </label>
    </form>
    <div>
     <button id='sub'>提交</button> <span id='error' style='color:red'></span>
    </div>
  </div>
</body>
<script>
  $ = function(id){
    return document.getElementById(id)
  }
  let xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    if(xhr.readyState===4&&xhr.status===200){
      let data = JSON.parse(xhr.response)
        console.log(data)
        if(data.user){
          // location.href = '/index/'
        }else{
          let t = document.getElementsByTagName('span');
          for (let i=0;i<t.length;i++){
            t[i].innerHTML = ''
          }
         for (item in data.msg){
           console.log(data.msg[item])
           document.getElementsByName(item)[0].nextSibling.innerHTML = data.msg[item]
         }
        }
    }
  }
  let avata = $('avata')
  let avata_img = document.getElementById('avata_img')
  avata.onchange = function() {
    let file_obj = this.files[0]
    let reader = new FileReader()
    reader.readAsDataURL(file_obj)
    reader.onload = function() {
      avata_img.setAttribute('src', reader.result)
    }
  }
  let subBtn = $('sub')
  subBtn.onclick = function() {
    let formData = new FormData($('form'))
    // formData.append("user", $('id_user').value)
    // formData.append("pwd", $('id_pwd').value)
    // formData.append("re_pwd", $('id_re_pwd').value)
    // formData.append("email", $('id_email').value)
    // formData.append("csrfmiddlewaretoken", document.getElementsByName('csrfmiddlewaretoken')[0].value)
    
    xhr.open('POST', '/register/', true)
    xhr.send(formData)

  }

</script>
</html>